package cn.tedu.ximart.server.ex.handler;

import cn.tedu.ximart.server.ex.ServiceException;
import cn.tedu.ximart.server.web.JsonResult;
import cn.tedu.ximart.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e){
        log.error("统一处理ServiceException,将向客户端响应：{}",e.getMessage());
        return JsonResult.fail(e);

    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e){
        log.debug("统一处理BindException,将向客户端响应：{}",e.getMessage());
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringJoiner stringJoiner = new StringJoiner(";");
        for(FieldError fieldError:fieldErrors){
            stringJoiner.add(fieldError.getDefaultMessage());
        }
        String message = stringJoiner.toString();
        return JsonResult.fail(ServiceCode.ERR_NOT_FOUND,message);
    }




    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        log.error("统一处理Throwable,将向客户端响应：{}",e.getClass().getName(),e.getMessage());
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN,e.getMessage());
    }
}
